class SoftwaresController < ApplicationController
#このコントローラ内のメソッドを行う前にログインチェック
  before_action :cheaklogin

       def cheaklogin
         if $logincheak == 0
             redirect_to login_path
         end
       end

  def index
    @softwares = Software.all
  end

#ソフトウェア名検索フォーム
  def search
      @softwares = Software.where('swname like ?', "%"+params[:q]+"%")
      render "index"
    end

  def show
    @software = Software.find(params[:id])
  end

  def new
    @software = Software.new
  end

  def create
    @software = Software.new(software_params)
 #新規登録のエラー処理
    if Software.find_by(:swid  => @software.swid)
            redirect_to new_software_path, :notice => "エラー！ソフトウェアIDが重複しています！"
    elsif @software.swid.empty? || @software.swname.empty? || @software.productkey.empty? || @software.license.nil?
      redirect_to new_software_path, :notice => "エラー！記入漏れがあります！"
    else
      if @software.save
        redirect_to softwares_url
      else
        render 'new'
      end
    end
  end

  def edit
    @software = Software.find(params[:id])
  end

  def update
    @software = Software.find(params[:id])
      if @software.update(software_params)
        redirect_to software_url(@software)
      else
        render 'edit'
      end
  end

  def destroy
    @software = Software.find(params[:id])
    @software.destroy
    redirect_to softwares_url
  end

  private
  def software_params
    params.require(:software).permit(:swid, :swname, :productkey, :license)
  end

end

